package com.pd.business.impl;

import com.pd.business.ResourceService;
import com.pd.dao.mapper.ResourceDao;
import com.pd.dao.model.ResourceDo;
import com.pd.dao.model.TreeNode;
import com.pd.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dong peng on 2018/1/24.
 */
@Service("resourceService")
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceDao resourceDao;

    public List<ResourceDo> query() {
        return resourceDao.selectResources();
    }

    @Override
    public List<TreeNode> queryTreeNode(Integer roleId) {
        List<ResourceDo> firstNode = resourceDao.selectRootNode();

        List<TreeNode> root = new ArrayList<>();
        for(ResourceDo resourceDo : firstNode) {
            TreeNode node = new TreeNode();
            node.setId(resourceDo.getId());
            node.setText(resourceDo.getResourceName());
            if(resourceDo.getHasIt() == 0) {
                node.setChecked(false);
            }else {
                node.setChecked(true);
            }
            findChildren(node,roleId);
            root.add(node);
        }
        return root;
    }

    private void findChildren(TreeNode node, Integer roleId) {
        List<ResourceDo> childrenList = resourceDao.selectByParentId(node.getId(),roleId);
        if(childrenList == null || childrenList.size() == 0) {
            return;
        }

        List<TreeNode> level = new ArrayList<>();
        for(ResourceDo resourceDo : childrenList) {
            TreeNode childNode = new TreeNode();
            childNode.setId(resourceDo.getId());
            childNode.setText(resourceDo.getResourceName());
            if(resourceDo.getHasIt() == 0) {
                node.setChecked(false);
            }else {
                node.setChecked(true);
            }
            // 递归查找
            this.findChildren(childNode,roleId);
            level.add(childNode);
        }

        node.setChildren(level);
    }

    public Integer add(ResourceDo resourceDo) {
        if(resourceDo == null || resourceDo.getResourceUrl() == null) {
            throw  new BusinessException("资源url不能为空");
        }
        ResourceDo oldRole = resourceDao.selectByUrl(resourceDo.getResourceUrl());
        if(oldRole != null) {
            throw  new BusinessException("该角色已存在");
        }
        return resourceDao.insertResource(resourceDo);
    }

    public Integer modify(ResourceDo resourceDo) {
        return resourceDao.updateResource(resourceDo);
    }

    public Integer delete(Integer id) {
        return resourceDao.deleteResource(id);
    }
}
